//
//  RecommendCustomerViewController.m
//  Kfangchan
//
//  Created by liran on 14/11/11.
//  Copyright (c) 2014年 Beijing Renjuren Network Technology Co., Ltd. All rights reserved.
//

#import "RecommendCustomerViewController.h"
#import "RecommendCustomerTableViewCell.h"
#import "NewCustomerViewController.h"
#import "UpdCustomerViewController.h"

@interface RecommendCustomerViewController () {
    UITapGestureRecognizer *tap;
    UIView *emptyView;
}

@property (nonatomic) int cpage;
@property (strong, nonatomic) NSMutableArray *customerArray;

@property (strong, nonatomic) IBOutlet UIView *searchView;
@property (strong, nonatomic) IBOutlet UITextField *searchTextField;
@property (strong, nonatomic) IBOutlet UIButton *searchButton;

@property (strong, nonatomic) IBOutlet UIView *customerView;
@property (strong, nonatomic) IBOutlet UITableView *customerTableView;

@end

@implementation RecommendCustomerViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.navigationItem.titleView = [[Theam currentTheam] navigationTitleViewWithTitle:@"推荐客户"];
    self.navigationItem.leftBarButtonItem = [[Theam currentTheam] navigationBarLeftButtonItemWithImage:[UIImage imageNamed:@"nav_back.png"] Target:self Selector:@selector(back)];
    
    [self.searchView cornerViewWithRectCorner:UIRectCornerAllCorners andCgSize:CGSizeMake(4, 4)];
    self.customerTableView.size = CGSizeMake(self.customerTableView.width, ScreenHeight - 110);
    
    __weak RecommendCustomerViewController *weak_self = self;
    //header
    [self.customerTableView addHeaderWithCallback:^{
        [weak_self initList];
    } andIsChat:YES andIsOther:YES];
    //footer
    [self.customerTableView addFooterWithCallback:^{
        weak_self.cpage++;
        [weak_self loadData];
    }];
    
    [self initEmptyView];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    if (self.customerArray == nil || self.customerArray.count == 0) {
        [self initList];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 列表相关
#pragma mark 初始化
- (void)initList {
    self.cpage = 1;
    if (self.customerArray == nil) {
        self.customerArray = [NSMutableArray array];
    }
    [self loadData];
}

#pragma mark 加载数据
- (void)loadData {
    __weak RecommendCustomerViewController *weak_self = self;
    NSDictionary *param = @{
                            @"cpage": [NSString stringWithFormat:@"%i", self.cpage],
                            @"name": self.searchTextField.text,
                            @"notInBuildingId": [NSString stringWithFormat:@"%i", self.buildingId]};
    MKNetworkOperation *operation = [[BaseEngine sharedEngine]RunRequest:[param mutableCopy] path:KFC_RECOMMEND_CUSTOMER_LIST completionHandler:^(id responseObject) {
        
        if (weak_self.cpage==1) {
            [weak_self.customerArray removeAllObjects];
        }
        
        id totalPages = [responseObject objectForKey:@"totalPages"];
        if (weak_self.cpage >= [totalPages intValue]) {
            [weak_self.customerTableView setFooterHidden:YES];
        } else {
            [weak_self.customerTableView setFooterHidden:NO];
        }
        
        id list = [responseObject objectForKey:@"list"];
        if (![list isKindOfClass:[NSNull class]]) {
            CustomerList *customerList = [[CustomerList alloc] initWithArray:list];
            [weak_self.customerArray addObjectsFromArray:customerList.array];
        }
        
        if (weak_self.customerArray.count == 0) {
            [weak_self.customerTableView addSubview:emptyView];
        } else {
            [emptyView removeFromSuperview];
        }
        
        [weak_self.customerTableView reloadData];
    } errorHandler:^(NSError *error) {
        showCustomAlertMessage(@"网路错误");
        [weak_self.customerTableView headerEndRefreshing];
        [weak_self.customerTableView setFooterHidden:YES];
    } finishHandler:^(id responseObject) {
        [weak_self.customerTableView headerEndRefreshing];
        [weak_self.customerTableView footerEndRefreshing];
    }];
    [self.opHandlers addObject:operation];
}

#pragma mark - UITableVIew
#pragma mark 设置行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.customerArray count];
}

#pragma mark 设置cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"RecommendCustomerTableViewCell";
    
    Customer *entity = self.customerArray[indexPath.row];
    
    RecommendCustomerTableViewCell *cell = (RecommendCustomerTableViewCell *)[tableView dequeueReusableCellWithIdentifier:identifier];
    
    if (cell == nil) {
        NSArray *cells = [[NSBundle mainBundle] loadNibNamed:identifier owner:self options:nil];
        cell = [cells objectAtIndex:0];
        
        cell.selectionStyle = UITableViewCellSelectionStyleGray;
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    
    [cell initCell:entity];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    int row = (int)[indexPath row];
    Customer *customer = self.customerArray[row];
    if (customer) {
        UpdCustomerViewController *ucv = [[UpdCustomerViewController alloc] init];
        ucv.customer = customer;
        ucv.buildingId = self.buildingId;
        [self.navigationController pushViewController:ucv animated:YES];
    }
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}

#pragma mark -
#pragma mark return键关闭键盘
- (IBAction)searchTextFieldDoneEditing:(id)sender {
    [self hideKeyboard];
    [self search];
}

#pragma mark 触摸背景关闭键盘
-(IBAction)tapBackground {
    if (tap == nil) {
        tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyboard)];//定义一个手势
        [tap setNumberOfTouchesRequired:1];//触击次数这里设为1
    }
    
    if([[self.view gestureRecognizers] containsObject:tap]) {
        return;
    }
    [self.view addGestureRecognizer:tap];
}

-(void)hideKeyboard {
    [self.searchTextField resignFirstResponder];
    [self.view removeGestureRecognizer:tap];
}

#pragma mark -
#pragma mark 搜索
- (IBAction)search {
    [self hideKeyboard];
    [self initList];
}

#pragma mark -
#pragma mark 空结果页
- (void)initEmptyView {
    if(emptyView == nil) {
        emptyView = [[UIView alloc] initWithFrame:self.customerView.bounds];
        UIImageView *emptyImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 45, 320, 211)];
        emptyImageView.image = [UIImage imageNamed:@"recommend_customer_empty.png"];
        [emptyView addSubview:emptyImageView];
    }
}

#pragma mark -
#pragma mark
- (void)back {
    [self.navigationController popViewControllerAnimated:YES];
}

@end
